package kafkautil;


import org.apache.kafka.clients.admin.AdminClient;
import org.apache.kafka.clients.admin.AdminClientConfig;
import org.apache.kafka.clients.admin.NewTopic;

import java.util.Collections;
import java.util.Properties;
import java.util.concurrent.ExecutionException;


/**
 * @author chaiduyixuan
 * @create 2023-06-18 18:50
 */
public class KafkaTopicCreator {
    public static void main(String[] args) {
        // Kafka 服务器地址
        String bootstrapServers = "192.168.81.133:9092";
        // 主题名称
        String topicName = "stuInfo1";
        // 分区数
        int numPartitions = 1;
        // 副本因子
        short replicationFactor = 1;

        // 配置 AdminClient
        Properties properties = new Properties();
        properties.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);

        // 创建 AdminClient
        try (AdminClient adminClient = AdminClient.create(properties)) {
            // 创建主题的配置
            NewTopic newTopic = new NewTopic(topicName, numPartitions, replicationFactor);

            // 创建主题
            adminClient.createTopics(Collections.singletonList(newTopic)).all().get();
            System.out.println("Topic created successfully.");
        } catch (InterruptedException | ExecutionException e) {
            System.out.println("Failed to create topic: " + e.getMessage());
        }
    }
}
